package es.xpt.ysf.view.collections;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import es.xpt.ysf.logging.LogManager;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "YSFCollections")
public class YSFCollections { 
	
	@XmlElement(required = true, name="collection")
    private List<CollectionInfo> collections;

	@XmlTransient
	private Map<String, CollectionInfo> map = null;
	@XmlTransient
	private InputStream file;


	public YSFCollections() {
		super();
		map = new HashMap<String, CollectionInfo>();
	}

	/**
	 * Construct a new {@link YSFCollections} instance.
	 */
	public YSFCollections(InputStream file) {
		super();
		map = new HashMap<String, CollectionInfo>();
		this.file = file;
	}

	public CollectionInfo get(String arg0) {
		return map.get(arg0);
	}


	public void parse() {
		try {
			JAXBContext jaxbContextResponse = JAXBContext.newInstance("es.xpt.ysf.view.collections");
			Unmarshaller unmarshaller = jaxbContextResponse.createUnmarshaller();
			YSFCollections instance = (YSFCollections) unmarshaller.unmarshal(file);
			for (CollectionInfo info : instance.getCollections()) {
				map.put(info.getName(), info);				
			}
			collections = instance.getCollections();
		} catch (JAXBException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
		}
	}
	
	public List<CollectionInfo> getCollections() {
        if (collections == null) {
        	collections = new ArrayList<CollectionInfo>();
        }
        return this.collections;
    }
	


}
